package com.qiangesoft.design.structural.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk动态代理
 */
public class JdkDynamicProxy {
    public static void main(String[] args) {
        RealDriver realDriver = new RealDriver();
        ProxyDriver proxyDriver = new ProxyDriver(realDriver);
        Driver proxy = (Driver) proxyDriver.getProxyInstance();
        // 使用代理对象来调用抽象方法
        proxy.drive("奥迪A6L");
    }
}

/**
 * 驾驶员接口
 */
interface Driver {
    void drive(String car);
}

/**
 * 真实驾驶员
 */
class RealDriver implements Driver {

    @Override
    public void drive(String car) {
        System.out.println("【" + car + "】被开回家了");
    }
}

/**
 * 代理驾驶员
 */
class ProxyDriver implements InvocationHandler {

    private Object realDriver;

    public ProxyDriver(RealDriver realDriver) {
        this.realDriver = realDriver;
    }

    public Object getProxyInstance() {
        // 使用Proxy类的静态方法newProxyInstance来动态地创建一个代理对象，传入真实主题对象的类加载器、接口和处理器
        return Proxy.newProxyInstance(realDriver.getClass().getClassLoader(), realDriver.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代驾取钥匙");

        Object result = method.invoke(realDriver, args);

        System.out.println("代驾还钥匙");
        return result;
    }
}